package com.leyou.trade.interceptors;

import com.leyou.common.constants.UserTokenConstants;
import com.leyou.common.entity.Payload;
import com.leyou.common.entity.UserInfo;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.common.utils.JwtUtils;
import com.leyou.trade.utils.UserHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * @author 虎哥
 */
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 1.获取token
        String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
        // 2.从token中解析用户
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, UserInfo.class);
        } catch (UnsupportedEncodingException e) {
            throw new LyException(400, "用户不能为空");
        }
        UserInfo userInfo = payload.getUserInfo();
        // 3.保存用户
        UserHolder.setUser(userInfo.getId());
        // 4.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 5.清除用户
        UserHolder.removeUser();
    }
}
